﻿using System;
using System.Data.Odbc;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using Cat;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyDBconnection;

namespace Thesis_2
{
    public partial class frmUserManager : Form
    {
        ConnectionString cs = new ConnectionString();
        OdbcConnection con = null;
        OdbcCommand cmd = null;
        OdbcDataReader rdr = null;
        DatabaseConnection dbcon = new DatabaseConnection();

        public frmUserManager()
        {
            InitializeComponent();
            //Tab1 button
            btnNewRecord.Click += new EventHandler(btnNewRecord_Click);
            btnRegister.Click += new EventHandler(btnRegister_Click);
            btnGetDetails.Click += new EventHandler(btnGetDetails_Click);
            btnCheckAvailability.Click += new EventHandler(btnCheckAvailability_Click);  
            //Tab1 Textbox
            txtEmail_Address.Validating += new CancelEventHandler(txtEmail_Address_Validating);
            txtUsername.Validating += new CancelEventHandler(txtUsername_Validating);
            txtName.KeyPress += new KeyPressEventHandler(txtName_KeyPress);
            txtContact_no.KeyPress += new KeyPressEventHandler(txtContact_no_KeyPress); 
            //Tab2 Textbox
            txtEmaiU.Validating += new CancelEventHandler(txtEmaiU_Validating);
            txtUsernameU.Validating += new CancelEventHandler(txtUsernameU_Validating);
            txtNameU.KeyPress += new KeyPressEventHandler(txtNameU_KeyPress);
            txtContactU.KeyPress += new KeyPressEventHandler(txtContactU_KeyPress);
            txtsearchuser.TextChanged += new EventHandler(txtsearchuser_TextChanged);
            //Tab2 button
            btnCheckU.Click += new EventHandler(btnCheckU_Click);
            btnClearU.Click += new EventHandler(btnClearU_Click);
            btnUpdateU.Click += new EventHandler(btnUpdateU_Click);
            //Tab2 grid
            dataGridView1.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_RowHeaderMouseClick);
            //Tab3 textbox
            txtCurrentPass.TextChanged += new EventHandler(txtCurrentPass_TextChanged);
            //tab3 button
            btnprocess.Click += new EventHandler(btnprocess_Click);
            btnreset.Click += new EventHandler(btnreset_Click);
            this.Load += new EventHandler(frmUserManager_Load);
        }
        //Tab3 button function
        void btnreset_Click(object sender, EventArgs e)
        {
            txtCurrentPass.Text = "";
            txtNewpass.Text = "";
            txtRepass.Text = "";
            txtNewpass.Enabled = false;
            txtRepass.Enabled = false;
        }
        void btnprocess_Click(object sender, EventArgs e)
        {
            if (txtCurrentPass.Text == "")
            {
                MessageBox.Show("Please enter current password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCurrentPass.Focus();
                return;

            }
            dbcon.dbconnection();
            dbcon.mylogin("SELECT * from tbluserinfo WHERE Username = '" + txtUser.Text + "' and Password= '" + txtCurrentPass.Text + "'");
            if (dbcon.tbl.Rows.Count > 0)
            {
                dbcon.DBClose();
                if (txtNewpass.Text == "")
                {
                    MessageBox.Show("Please Enter New password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewpass.Focus();
                    return;

                }
                if (txtNewpass.TextLength < 5)
                {
                    MessageBox.Show("The New Password Should be of Atleast 5 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewpass.Focus();
                    return;

                }
                if (txtRepass.Text == "")
                {
                    MessageBox.Show("Please Confirm password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtRepass.Focus();
                    return;

                }
                if (txtNewpass.Text != txtRepass.Text)
                {
                    MessageBox.Show("Password do not match", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCurrentPass.Text = "";
                    txtNewpass.Text = "";
                    txtRepass.Text = "";
                    txtCurrentPass.Focus();
                    return;
                }
                if (txtNewpass.Text == txtCurrentPass.Text)
                {
                    MessageBox.Show("Your New password is the same with your current password Please Enter new password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewpass.Text = "";
                    txtRepass.Text = "";
                    txtNewpass.Focus();
                    return;
                }
                dbcon.dbconnection();
                dbcon.UpdateData("Update tbluserinfo set Password='" + txtNewpass.Text + "' Where Username='" + txtUser.Text + "';");
                MessageBox.Show("Update Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                dbcon.DBClose();
            }
            else
            {

                label1.Text = "Current password incorrect";
                txtCurrentPass.Text = "";
                txtNewpass.Text = "";
                txtRepass.Text = "";
                txtCurrentPass.Focus();
                dbcon.DBClose();
                return;
            }
        }
        //tab3 textbox function
        void txtCurrentPass_TextChanged(object sender, EventArgs e)
        {
            if (txtCurrentPass.Text != "")
            {
                txtNewpass.Enabled = true;
                txtRepass.Enabled = true;
                return;
            }
            else
            {
                txtNewpass.Enabled = false;
                txtRepass.Enabled = false;
            }
        }
        //Tab2 Textbox Function
        void txtsearchuser_TextChanged(object sender, EventArgs e)
        {
            if (txtsearchuser.Text != "Search User")
            {
                dbcon.dbconnection();
                dbcon.loadData("SELECT distinct Username,Name,ContactNo,Email,Usertype,JoiningDate FROM tbluserinfo WHERE Username LIKE '%" + txtsearchuser.Text + "%'");
                dataGridView1.DataSource = dbcon.tbl;
                dbcon.DBClose();
            }
            else
            {
                Getdata();
            }
            
        }
        void txtContactU_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        void txtNameU_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
        }
        void txtUsernameU_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9_]");
            if (txtUsername.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtUsernameU.Text))
                {
                    MessageBox.Show("Only letters,numbers and underscore is allowed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUsernameU.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        void txtEmaiU_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail_Address.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmaiU.Text))
                {
                    MessageBox.Show("Invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmaiU.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow dr = dataGridView1.SelectedRows[0];
            txtuserID.Text = dr.Cells[0].Value.ToString();
            txtUsernameU.Text = dr.Cells[0].Value.ToString();
            txtNameU.Text = dr.Cells[1].Value.ToString();
            txtContactU.Text = dr.Cells[2].Value.ToString();
            txtEmaiU.Text =dr.Cells[3].Value.ToString();
            cmbusertypeU.Text = dr.Cells[4].Value.ToString();
        }
        //Tab2 Button Funtion
        void btnUpdateU_Click(object sender, EventArgs e)
        {
            if (txtUsernameU.Text == "")
            {
                MessageBox.Show("Please Enter UserName to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUsernameU.Focus();
                return;
            }
            if (cmbusertypeU.Text == "")
            {
                MessageBox.Show("Please Select Usertype to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbusertypeU.Focus();
                return;
            }
            if (txtNameU.Text == "")
            {
                MessageBox.Show("Please Enter Name to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtNameU.Focus();
                return;
            }
            if (txtContactU.Text == "")
            {
                MessageBox.Show("Please Enter Contact No. to Update ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContactU.Focus();
                return;
            }
            dbcon.dbconnection();
            dbcon.UpdateData("Update tbluserinfo set Username='" + txtUsernameU.Text + "', Name = '" + txtNameU.Text+ "' ,ContactNo = '" + txtContactU.Text + "', Email = '" + txtEmaiU.Text + "',Usertype = '" + cmbusertypeU.Text + "'Where Username='" + txtuserID.Text + "';");
            MessageBox.Show("Update Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            resetTab2();
            dbcon.DBClose();
            Getdata();
        }
        void btnClearU_Click(object sender, EventArgs e)
        {
            resetTab2();
        }
        void btnCheckU_Click(object sender, EventArgs e)
        {
            checkUpdate();
        }
        //Tab1 Button Fucntion
        void btnNewRecord_Click(object sender, EventArgs e)
        {
            reset();
        }
        void btnCheckAvailability_Click(object sender, EventArgs e)
        {
            check();
        }
        void btnRegister_Click(object sender, EventArgs e)
        {
            #region error trap
            if (txtUsername.Text == "")
            {
                MessageBox.Show("Please enter username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUsername.Focus();
                return;
            }
            if (cmbUserType.Text == "")
            {
                MessageBox.Show("Please select user type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbUserType.Focus();
                return;
            }
            if (txtPassword.Text == "")
            {
                MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }
            if (txtPassword.TextLength < 5)
            {
                MessageBox.Show("The New Password Should be of Atleast 5 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }
            if (txtName.Text == "")
            {
                MessageBox.Show("Please enter name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtName.Focus();
                return;
            }
            if (txtContact_no.Text == "")
            {
                MessageBox.Show("Please enter contact no.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContact_no.Focus();
                return;
            }
            if (txtEmail_Address.Text == "")
            {
                MessageBox.Show("Please enter email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail_Address.Focus();
                return;
            }
            #endregion
            try
            {
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct = "Select Username from tbluserinfo where Username='" + txtUsername.Text + "'";
                cmd = new OdbcCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Username Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUsername.Text = "";
                    txtUsername.Focus();

                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    return;
                }
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct1 = "Select Email from tbluserinfo where Email='" + txtEmail_Address.Text + "'";
                cmd = new OdbcCommand(ct1);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Email ID Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail_Address.Text = "";
                    txtEmail_Address.Focus();


                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    return;

                }
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string cb = "Insert into tbluserinfo(Username,Password,Name,ContactNo,Email,Usertype) VALUES ('" + txtUsername.Text + "','" + txtPassword.Text + "','" + txtName.Text + "','" + txtContact_no.Text + "','" + txtEmail_Address.Text + "','" + cmbUserType.Text + "')";

                cmd = new OdbcCommand(cb);
                cmd.Connection = con;
                cmd.ExecuteReader();
                con.Close();
                MessageBox.Show("Successfully Registered", "User", MessageBoxButtons.OK, MessageBoxIcon.Information);

                btnRegister.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void btnGetDetails_Click(object sender, EventArgs e)
        {
            frmListofuser frmL = new frmListofuser();
            frmL.Show();
            this.Hide();
        }
        //Tab1 Textbox function
        void txtContact_no_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        void txtName_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
        }
        void txtUsername_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9_]");
            if (txtUsername.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtUsername.Text))
                {
                    MessageBox.Show("Only letters,numbers and underscore is allowed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUsername.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        void txtEmail_Address_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail_Address.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmail_Address.Text))
                {
                    MessageBox.Show("Invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail_Address.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        // Reset Method
        //Tab1
        void reset()
        {
            txtUsername.Text = "";
            cmbUserType.SelectedIndex = -1;
            txtPassword.Text = "";
            txtContact_no.Text = "";
            txtName.Text = "";
            txtEmail_Address.Text = "";
            txtUsername.Focus();
           
        }
        //Tab2
        void resetTab2()
        {
            txtUsernameU.Text = "";
            txtNameU.Text = "";
            cmbusertypeU.SelectedIndex = -1;
            txtContactU.Text = "";
            txtEmaiU.Text = "";
        }
        //loading user info from database
        void Getdata()
        {
            dbcon.dbconnection();
            dbcon.loadData("Select distinct Username,Name,ContactNo,Email,Usertype,JoiningDate from tbluserinfo");
            dataGridView1.DataSource = dbcon.tbl;
            dbcon.DBClose();
        }
        //Username in update
        void checkUpdate()
        { 
            try
            {
                if (txtUsernameU.Text == "")
                {
                    MessageBox.Show("Please enter Username to Update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUsernameU.Focus();
                    return;
                }
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct = "Select Username from tbluserinfo where Username='" + txtUsernameU.Text + "'";
                cmd = new OdbcCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Username not available", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (!rdr.Read())
                {
                    MessageBox.Show("Username available", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtUsernameU.Focus();

                }
                if ((rdr != null))
                {
                    rdr.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }           
        //Username Availability
        void check()
        {
            try
            {
                if (txtUsername.Text == "")
                {
                    MessageBox.Show("Please enter username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUsername.Focus();
                    return;
                }
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct = "Select Username from tbluserinfo where Username='" + txtUsername.Text + "'";
                cmd = new OdbcCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Username not available", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (!rdr.Read())
                {
                    MessageBox.Show("Username available", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtUsername.Focus();

                }
                if ((rdr != null))
                {
                    rdr.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }
        void userlog()
        {
            con = new OdbcConnection(cs.DBConn);
            con.Open();
            string us = "Select * from tbluserlog";
            cmd = new OdbcCommand(us);
            cmd.Connection = con;
            rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                txtUser.Text = (rdr["Username"].ToString());


            }

        }
        void frmUserManager_Load(object sender, EventArgs e)
        {
            Getdata();
            userlog();
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        }
     
    }
}
